package com.esd.crm.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.esd.common.util.UsernameAndPasswordMd5;
import com.esd.crm.Constants;
import com.esd.crm.entity.User;
import com.esd.crm.service.UserService;

/**
 * 入口界面，登录
 * 
 * @author snailzhang
 *
 */
@Controller
public class IndexController {

	private static final Logger logger = LogManager.getLogger(IndexController.class);

	@Autowired
	private UserService userService;
	
	/**
	 * 用户名不存在
	 */
	@Value("${MSG_USER_NOT_EXIST}")
	private String MSG_USER_NOT_EXIST;

	/**
	 * 用户不能为空
	 */
	@Value("${MSG_USER_NOT_EMPTY}")
	private String MSG_USER_NOT_EMPTY;

	/**
	 * 密码不能为空
	 */
	@Value("${MSG_PASSWORD_NOT_EMPTY}")
	private String MSG_PASSWORD_NOT_EMPTY;

	/**
	 * 密码错误
	 */
	@Value("${MSG_PASSWORD_NOT_ERROR}")
	private String MSG_PASSWORD_NOT_ERROR;
	/**
	 * 用户已停用
	 */
	@Value("${MSG_USER_STOP}")
	private String MSG_USER_STOP;

	/**
	 * 登录页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String loginGet() {
		logger.info("跳转到登录页");
//		return new ModelAndView("login");
        return "login";
	}
	/**
	 * 退出页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/quit", method = RequestMethod.GET)
	public ModelAndView quitGet(HttpSession session) {
		session.removeAttribute(Constants.USER_ID);
		session.removeAttribute(Constants.USER_NAME);
		session.removeAttribute(Constants.USER_TYPE);
		session.removeAttribute(Constants.ADD_USER_ID);
		return new ModelAndView(Constants.REDIRECT + Constants.COLON + Constants.LOGIN);
	}

	/**
	 * 验证用户名是否存在
	 * 
	 * @param username
	 * @return
	 */
	@RequestMapping(value = "/checkUserName", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> checkUserName(String username) {

		return checkLoginName(username);
	}

	/**
	 * 验证用户名密码,跳转响应页面
	 * 
	 * @param username
	 * @param password
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public ModelAndView loginPost(String username, String password, RedirectAttributes redirectAttributes, HttpSession session, HttpServletRequest request) {
//		System.out.println("username:"+username+",password:"+password);
		if (StringUtils.isBlank(username)) {
			redirectAttributes.addFlashAttribute(Constants.MESSAGE, MSG_USER_NOT_EMPTY);
		}
		if (StringUtils.isBlank(password)) {
			redirectAttributes.addFlashAttribute(Constants.MESSAGE, MSG_PASSWORD_NOT_EMPTY);
		}
		User user = userService.findOneByUserName(username);
//		System.out.println("user===>"+user);
		if (user == null) {
			redirectAttributes.addFlashAttribute(Constants.MESSAGE, MSG_USER_NOT_EXIST);
		} else {
			if (user.getUserStatus() == false) {
				redirectAttributes.addFlashAttribute(Constants.MESSAGE, MSG_USER_STOP);
				redirectAttributes.addFlashAttribute(Constants.USER_NAME, username);
				return new ModelAndView(Constants.REDIRECT + Constants.COLON + Constants.LOGIN);
			}
			UsernameAndPasswordMd5 md5 = new UsernameAndPasswordMd5();
			String md5Password = md5.getMd5(username, password);
			logger.debug("md5Password:{}");
			System.out.println("md5Password:{}"+ md5Password);
			// 密码比较
			if (md5Password.equals(user.getPassword())) {
				session.setAttribute(Constants.USER_NAME, user.getUsername());
				session.setAttribute(Constants.USER_ID, user.getId());
				session.setAttribute(Constants.USER_TYPE,user.getUserType());
				//if (username.equals("admin")) {
					//session.setAttribute(Constants.USER_TYPE,"0");
					//return new ModelAndView(Constants.REDIRECT + Constants.COLON + Constants.SECURITY + Constants.SLASH + "manager");
				//}
				return new ModelAndView(Constants.REDIRECT + Constants.COLON  + Constants.SLASH + "mainPage");
			} else {
				redirectAttributes.addFlashAttribute(Constants.MESSAGE, MSG_PASSWORD_NOT_ERROR);
			}
		}
		redirectAttributes.addFlashAttribute(Constants.USER_NAME, username);
		redirectAttributes.addFlashAttribute(Constants.USER_PASSWORD, password);
		return new ModelAndView(Constants.REDIRECT + Constants.COLON + Constants.LOGIN);
	}

	/**
	 * 检测用户名
	 * 
	 * @param username
	 * @return
	 */
	public Map<String, Object> checkLoginName(String username) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (!StringUtils.isEmpty(username)) {
			User user = userService.findOneByUserName(username);
			if (user == null) {
				map.clear();
				map.put(Constants.MESSAGE, MSG_USER_NOT_EXIST);
				map.put(Constants.REPLAY, Constants.ZERO);
				return map;
			}
			if (user.getUserStatus() == false) {
				map.clear();
				map.put(Constants.MESSAGE, MSG_USER_STOP);
				map.put(Constants.REPLAY, Constants.ZERO);
				return map;
			}
			map.clear();
			map.put(Constants.REPLAY, Constants.ONE);
		}
		return map;
	}
	/**
	 * 跳转菜单页
	 * @return
	 */
	@RequestMapping(value = "/mainPage", method = RequestMethod.GET)
	public String mainPage() {
		return "main";
	}
	
	
	public static void main(String[] args) {
		UsernameAndPasswordMd5 md5 = new UsernameAndPasswordMd5();
		String md5Password = md5.getMd5("fewfew", "123123");
		System.out.println(md5Password);
	}
}
